package com.mao.dao.productstock;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mao.action.jsonvo.searchcenter.JsonVoSearchProductStock;
import com.mao.dao.BaseDAOHibernate;
import com.mao.model.product.Product;
import com.mao.model.warehouse.WareHouse;
import com.mao.service.impl.productstock.ProductStockCondition;
import com.mao.service.impl.searchvoucher.SearchStockCondition;
import com.mao.service.impl.searchvoucher.SearchVoucherCondition;
import com.mao.service.product.IProductService;
import com.mao.service.searchvoucher.ISearchVoucherService;
import com.mao.util.SessionHelper;
import com.mao.util.Validator;

@Component("productStockDao")
public class ProductStockDao extends BaseDAOHibernate {

	private IProductService productService;
	
	private ISearchVoucherService searchVoucherService;
	
	
	/**
	 * 
	 *  Created on 2012-11-28 
	 * <p>Discription:[库存明细查询]</p>
	 * @author:[沈晓超]
	 * @param pro
	 * @return List<JsonVoSearchProductStock>
	 */
	public	List<JsonVoSearchProductStock> findStocksByPro(SearchVoucherCondition seachVoucherCondition) {
		Session wareHouseSession = this.getSession();
		StringBuilder hql = new StringBuilder();
		hql.append("from WareHouse wh where wh.status='" + WareHouse.STATUS_NORMAL + "' and wh.store.id=" + SessionHelper.getSessionUser().getStore().getId());
		if(!Validator.isEmpty(seachVoucherCondition.getWhId())){
			hql.append(" and wh.id=" + seachVoucherCondition.getWhId());
		}
		Query wareHouseQuery = wareHouseSession.createQuery(hql.toString());
		List<WareHouse> wareHouselist = wareHouseQuery.list();
		JsonVoSearchProductStock jsps = null;
		List<JsonVoSearchProductStock> result = new ArrayList<JsonVoSearchProductStock>();
		boolean flag = true;
		SearchStockCondition ssc = null;
		for(WareHouse wh : wareHouselist){
			jsps = new JsonVoSearchProductStock();
			// Condition
			ssc = new SearchStockCondition();  
			ssc.setProductId(seachVoucherCondition.getPro().getId());
			ssc.setWareHouseId(wh.getId());
			ssc.setStime(seachVoucherCondition.getStime());
			ssc.setEtime(seachVoucherCondition.getEtime());
			// vo
			jsps.setPurchaseNum(searchVoucherService.getWareHouseNumByProId(ssc));
			jsps.setrPurchaseNum(searchVoucherService.getReturnWareHouseNumByProId(ssc));
			jsps.setSaleNum(searchVoucherService.getDeliveryNumByPorId(ssc));
			jsps.setrSaleNum(searchVoucherService.getReturnDeliveryNumByProId(ssc));
			jsps.setWarehouse(wh.getName());
			jsps.setWareHouseId(wh.getId());
			jsps.setInitStock(0);
			if(seachVoucherCondition.getPro().getInitWareHouse() != null && seachVoucherCondition.getPro().getInitWareHouse().getId() == wh.getId()){
				flag = false;
				jsps.setInitStock(seachVoucherCondition.getPro().getInitStock());
			}
			jsps.setStock((jsps.getPurchaseNum() - jsps.getrPurchaseNum()) - (jsps.getSaleNum() - jsps.getrSaleNum()) + jsps.getInitStock());
			if(jsps.getPurchaseNum() != 0 || jsps.getrPurchaseNum() != 0 || jsps.getSaleNum() != 0 || jsps.getrSaleNum() != 0 || jsps.getInitStock() != 0){
				result.add(jsps);
			}
			
		}
		// 判断初始化仓库是否已放进list，没的话另外加一条，主要判读初始仓库的ID是否已存在list里
		if(flag && seachVoucherCondition.getPro().getInitWareHouse()!=null){
			jsps = new JsonVoSearchProductStock();
			jsps.setPurchaseNum(0);
			jsps.setrPurchaseNum(0);
			jsps.setSaleNum(0);
			jsps.setrSaleNum(0);
			jsps.setStock(seachVoucherCondition.getPro().getInitStock());
			jsps.setInitStock(seachVoucherCondition.getPro().getInitStock());
			jsps.setWarehouse(seachVoucherCondition.getPro().getInitWareHouse().getName());
			jsps.setWareHouseId(seachVoucherCondition.getPro().getInitWareHouse().getId());
			result.add(jsps); 
		}
		// 查不到库存信息
		if(result.size() == 0){
			jsps = new JsonVoSearchProductStock();
			jsps.setWarehouse("无");
			jsps.setPurchaseNum(0);
			jsps.setrPurchaseNum(0);
			jsps.setSaleNum(0);
			jsps.setrSaleNum(0);  
			jsps.setStock(0);
			jsps.setInitStock(0);
			result.add(jsps);
		}
		return result;
	}

	/**
	 * 
	 *  Created on 2012-11-28 
	 * <p>Discription:[库存查询]</p>
	 * @author:[沈晓超]
	 * @param psd
	 * @param page
	 * @param rows
	 * @return List<JsonVoSearchProductStock>
	 */
	public List<JsonVoSearchProductStock> searchStockByPcId(ProductStockCondition psd,Integer page, Integer rows) {
		Session session = this.getSession();
		StringBuilder hql = new StringBuilder();
		hql.append("FROM Product p WHERE p.status='" + Product.STATUS_NORMAL +"' and p.store.id=" + SessionHelper.getSessionUser().getStore().getId());
		if (!Validator.isEmpty(psd.getTreePath())) {
			hql.append(" and p.proClass.treePath like '%" + psd.getTreePath() + "%'");
		}
		if (!Validator.isEmpty(psd.getSearchProName())) {
			hql.append(" and p.name like '%" + psd.getSearchProName().trim() + "%'");
		}
		Query query = session.createQuery(hql.toString());
		query.setFirstResult((page - 1) * rows);
		query.setMaxResults(rows);
		List<Product> list = query.list();  
		JsonVoSearchProductStock jsps = null;
		SearchStockCondition ssc = null;
		List<JsonVoSearchProductStock> result = new ArrayList<JsonVoSearchProductStock>();
		for(Product p : list) {
			jsps = new JsonVoSearchProductStock();
			// condition
			ssc = new SearchStockCondition();
			ssc.setProductId(p.getId());
			ssc.setStime(psd.getStime());
			ssc.setEtime(psd.getEtime());
			ssc.setProName(psd.getSearchProName());
			// vo
			jsps.setProName(p.getName());
			jsps.setProNo(p.getProNo());
			jsps.setSpec(p.getSpec());
			jsps.setPurchaseNum(searchVoucherService.getWareHouseNumByProId(ssc));
			jsps.setrPurchaseNum(searchVoucherService.getReturnWareHouseNumByProId(ssc));
			jsps.setSaleNum(searchVoucherService.getDeliveryNumByPorId(ssc));
			jsps.setrSaleNum(searchVoucherService.getReturnDeliveryNumByProId(ssc));
			jsps.setPid(p.getId());
			// 库存计算公式:进货总量-进货退货总量-（销售总量-销售退货总量）
			jsps.setStock((jsps.getPurchaseNum() - jsps.getrPurchaseNum()) - (jsps.getSaleNum() - jsps.getrSaleNum())); 
			if(p.getInitStock() != null){
				jsps.setStock(jsps.getStock() + p.getInitStock());
			}
			jsps.setProClassName(p.getProClass().getName());
			result.add(jsps);
		}
		return result;
	}
	
	public Integer searchStockByPcIdCount(ProductStockCondition psd) {
		Session session = this.getSession();
		StringBuilder hql = new StringBuilder();
		hql.append("FROM Product p WHERE p.status='" + Product.STATUS_NORMAL +"' and p.store.id=" + SessionHelper.getSessionUser().getStore().getId());
		if (!Validator.isEmpty(psd.getTreePath())) {
			hql.append(" and p.proClass.treePath like '%" + psd.getTreePath() + "%'");
		}
		if (!Validator.isEmpty(psd.getSearchProName())) {
			hql.append(" and p.name like '%" + psd.getSearchProName().trim() + "%'");
		}
		Query query = session.createQuery(hql.toString());
		return query.list().size();
	}

	public IProductService getProductService() {
		return productService;
	}

	@Autowired
	public void setProductService(IProductService productService) {
		this.productService = productService;
	}

	public ISearchVoucherService getSearchVoucherService() {
		return searchVoucherService;
	}
	
	@Autowired
	public void setSearchVoucherService(ISearchVoucherService searchVoucherService) {
		this.searchVoucherService = searchVoucherService;
	}
	
	

	
}
